package omg.loot;

import java.util.Random;


public class GameRunnable implements Runnable {
   //statics
   public static final Random rami = new Random();
   
   //Delta:
   static final double divider = 1000000;
   long lastLoopTime;
   double delta;
   short viive = 0; //Aika, jonka silmukka nukkuu (ms) - muuta kohdekestoa jos haluat muutoksia!
   static final short kohdekesto = 30; //Aika, joka pyritään saamaan silmukan kestoksi (ms)

   protected Renderer renderer;
   protected KeyReader key = new KeyReader(this);
   protected MouseReader mouse = new MouseReader();
   //Camera:
   Camera cam = new Camera(mouse);

   boolean run = true;
   boolean pause = false;

   protected Entity[] entities;
   protected Map map = new Map();
   protected Vohveli v[];
   
   Tile start;
   Tile end;

   public GameRunnable() {
      start = new Tile(1,1);
      end = new Tile(45,45);
      v = new Vohveli[1]; 
      v[0] = new Vohveli(start.x,start.y,32);
      v[0].tmp = map.aCross(start, end);
      v[0].start = v[0].tmp;
   }

   @Override
   public void run() { 
      calculateDelta();
      while (run) {
         calculateDelta();
         cam.updateCamera(delta);
         move();
         renderer.repaint();
         tauko();
         try { //Katsotaan ollaanko pausella:
            while (pause) {
               Thread.sleep(Long.MAX_VALUE); //Nukutaan kunnes keskeytetään
               lastLoopTime = System.nanoTime();
            }
         } catch (final InterruptedException ex) {
            lastLoopTime = System.nanoTime();
         } //Jos pause keskeytettiin, hypätään ulos silmukasta
      }
   }

   public void calculateDelta() {
      delta = (System.nanoTime() - lastLoopTime)/divider;
      lastLoopTime = System.nanoTime();
   }

   public void tauko() { //Suorituksen hidastaminen
      viive = (short)(kohdekesto-((System.nanoTime() - lastLoopTime)/divider));
      if (viive < 0)
         viive = 0;
      try { //Viivästetään suoritusta
         Thread.sleep(viive);
      } catch (final InterruptedException ex) {}
   } //tauko() ---------------------------------------------------

   public void newWave(){
      for(int i = 0; i < entities.length; i++)
         entities[i] = new Entity(rami.nextInt(Main.WIDTH),rami.nextInt(Main.HEIGHT),rami.nextInt(7)+3);
   }
   
   public void move(){
      v[0].move();
   }

}